package moni.anyou.com.view.view.account;
import android.annotation.TargetApi;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;
import org.json.JSONObject;
import org.kymjs.aframe.http.KJHttp;
import org.kymjs.aframe.http.KJStringParams;
import org.kymjs.aframe.http.StringCallBack;
import moni.anyou.com.view.R;
import moni.anyou.com.view.base.BaseActivity;
import moni.anyou.com.view.bean.request.ReqsUpdateLoginPwdBean;
import moni.anyou.com.view.config.SysConfig;
import moni.anyou.com.view.tool.ToastTools;
import moni.anyou.com.view.tool.VerificationTools;
import moni.anyou.com.view.widget.NetProgressWindowDialog;

import java.lang.reflect.Field;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.ScheduledExecutorService;
import android.os.Handler;

import com.readystatesoftware.systembartint.SystemBarTintManager;

public class ForgetPwdActivity extends BaseActivity implements View.OnClickListener {

    private EditText etMobile;
    private EditText etVerifyCode;
    private Button btnCommit;
    private NetProgressWindowDialog window;
    private String mobile;
    private String verifyCode;
    private ScheduledExecutorService scheduler = null;
    private int currSecond = 60;
    private Handler taskHandler = new Handler();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_forgetpwd);
        initState();
        initWindow();
        init();
    }

    @Override
    public void initView() {
        super.initView();
        initTitle();
        tvTitle.setText("忘记密码");
        tvRight.setVisibility(View.VISIBLE);
        tvRight.setText("确定");
        etMobile = (EditText) findViewById(R.id.et_mobile);
        etVerifyCode = (EditText) findViewById(R.id.et_verifycode);

        btnCommit = (Button) findViewById(R.id.btn_commit);
        window = new NetProgressWindowDialog(mBaseActivity);
    }

    @Override
    public void setAction() {
        super.setAction();
        btnCommit.setOnClickListener(this);
        tvRight.setOnClickListener(this);
        ivBack.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_commit:
                sendVerifyCode();
                break;
            case R.id.right_tv:
                postDate();
                break;
            case R.id.iv_left:
                onBack();
                break;
        }
    }


    private void postDate() {
        mobile = etMobile.getText().toString();
        verifyCode = etVerifyCode.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            ToastTools.showShort(mContext, "手机号不能为空！");
            return;
        }
        if (VerificationTools.isPhone(mobile.trim())) {
            ToastTools.showShort(mContext, "请输入正确的手机号！！");
            return;
        }
        if (TextUtils.isEmpty(verifyCode)) {
            ToastTools.showShort(mContext, "验证码不能为空！");
            return;
        }

        updatePwdPost();
    }
    // 切换当前显示的图片
    private Handler handler = new Handler() {
        public void handleMessage(android.os.Message msg) {
            //Toast.makeText(mcontext, "hello--"+currSecond, Toast.LENGTH_LONG).show();;// 切换当前显示的图片

            if (currSecond ==60){
                btnCommit.setText("发送验证码");

                btnCommit.setEnabled(true);
            }
            else{
                btnCommit.setText(currSecond+"秒后重新发送");
            }
        };
    };
    /**
     * 换行切换任务
     *
     * @author Administrator
     *
     */
    private class SendTask implements Runnable {

        public void run() {
           // System.out.println("currentSend: " + currSecond);
            currSecond = currSecond-1;
            if (currSecond <=0){
                scheduler.shutdown();
                currSecond = 60;
            }

            handler.obtainMessage().sendToTarget(); // 通过Handler发送消息

        }

    }

    public void sendVerifyCode() {
        mobile = etMobile.getText().toString();
        if (TextUtils.isEmpty(mobile)) {
            ToastTools.showShort(mContext, "手机号不能为空！");
            return;
        }
        if (VerificationTools.isPhone(mobile.trim())) {
            ToastTools.showShort(mContext, "请输入正确的手机号！！");
            return;
        }
        btnCommit.setText("60秒后重新发送");
        btnCommit.setEnabled(false);
        scheduler = Executors.newSingleThreadScheduledExecutor();
        // 当Activity显示出来后，每两秒钟切换一次图片显示
       scheduler.scheduleAtFixedRate(new SendTask(), 1, 1,
               TimeUnit.SECONDS);
        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        params.put("sendMsg", "{\"cmd\":\"3\",\"mobile\":\"" + mobile + "\"}");
        kjh.urlPost(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {
                try {
                    JSONObject jsonObject = null;
                    jsonObject = new JSONObject(t);
                    if (Integer.parseInt(jsonObject.getString("result")) < 1) {
                        scheduler.shutdown();
                        currSecond = 60;
                        btnCommit.setText("发送验证码");
                        btnCommit.setEnabled(true);
                        Toast.makeText(mContext, jsonObject.getString("retmsg"), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception ex) {

                }

            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {

                // window.closeWindow();
            }
        });
    }



    //手机高版本样式
    private void initState() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            //透明状态栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            //透明导航栏
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
        }

    }

    private SystemBarTintManager tintManager;
    //手机高版本样式
    @TargetApi(19)
    private void initWindow() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            getWindow().addFlags(
                    WindowManager.LayoutParams.FLAG_TRANSLUCENT_NAVIGATION);
            tintManager = new SystemBarTintManager(this);
            tintManager.setStatusBarTintColor(Color.parseColor("#FEC600"));

            tintManager.setStatusBarTintEnabled(true);
        }
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            try {
                Class decorViewClazz = Class.forName("com.android.internal.policy.DecorView");
                Field field = decorViewClazz.getDeclaredField("mSemiTransparentStatusBarColor");
                field.setAccessible(true);
                field.setInt(getWindow().getDecorView(),
                        Color.TRANSPARENT);
            } catch (Exception e) {
            }
        }

    }


    public void updatePwdPost() {

        KJHttp kjh = new KJHttp();
        KJStringParams params = new KJStringParams();
        String cmdPara = "{\"cmd\":\"32\",\"mobile\":\"" + mobile + "\",\"verifycode\":\"" + verifyCode + "\"}";
        params.put("sendMsg", cmdPara);
        window.ShowWindow();
        kjh.urlGet(SysConfig.ServerUrl, params, new StringCallBack() {
            @Override
            public void onSuccess(String t) {

                Log.d(TAG, "onSuccess: " + t);
                try {
                    JSONObject jsonObject = new JSONObject(t);
                    //Toast.makeText(mContext, t, Toast.LENGTH_LONG).show();
                    int result = Integer.parseInt(jsonObject.getString("result"));
                    if (result >= 1) {
                        Toast.makeText(mContext,jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                        onBack();
                    } else {
                        Toast.makeText(mContext, jsonObject.get("retmsg").toString(), Toast.LENGTH_LONG).show();
                    }
                } catch (Exception ex) {
                    Toast.makeText(mContext, "数据请求失败", Toast.LENGTH_LONG).show();

                }
                window.closeWindow();
            }

            @Override
            public void onFailure(Throwable t, int errorNo, String strMsg) {
                Toast.makeText(mContext, "网络异常，请稍后再试", Toast.LENGTH_LONG).show();

                window.closeWindow();
            }
        });
    }
}
